<template>
  <view class="register">
    <u-form :model="user" label-width='auto' ref='uForm'>
      <u-form-item required label="用户名" prop='username'>
        <u-input v-model="user.username"></u-input>
      </u-form-item>
      <u-form-item required label="密码" prop='password'>
        <u-input v-model="user.password" type="password"></u-input>
      </u-form-item>
      <u-form-item class="option">
          <u-button @click="toLogin" type="primary" size="medium">登录</u-button>
          <text class="toRegister" @click="toRegister">去注册</text>
      </u-form-item>
    </u-form>
    <u-toast ref="uToast" />
  </view>
</template>

<script>
  
  import { login } from './_api.js'
  
  import store from '@/store'
  export default {
    data () {
      return {
        user: {
          username: null,
          password: null,
        },
        rules: {
          username: [
            {
              required: true,
              message: '请输入用户名',
              trigger: ['blur', 'change']
            }
          ],
          password: [
            {
              min: 6,
              max: 18,
              required: true,
              message: '请输入6-18位密码',
              trigger: 'blur, change'
            }
          ]
        }
      }
    },
    methods: {
      toLogin() {
        this.$refs.uForm.validate(valid => {
          if (valid) {
            login(this.user)
              .then(res => {
                uni.setStorageSync('token',res.data.token)
                store.commit('SET_TOKEN', res.data.token)
                this.$refs.uToast.show({
                  title: '登录成功，正在跳转到首页',
                  type: 'success' 
                })
                uni.switchTab({
                  url: '/pages/index/index'
                })
              })
              .catch(err => {
                // 未注册则是报300
                if (err.code === 300) {
                  uni.showToast({
                    title: `err.message`,
                    icon: 'none'
                  })
                }
              })
          } else {
            uni.showToast({
              title:'请检查后再试',
              icon: 'none'
            })
          }
        })
        
      },
      
      toRegister() {
        uni.navigateTo({
          url: '/pages/register/index'
        })
      }
    },
    onReady() {
      this.$refs.uForm.setRules(this.rules);
    }
  }
</script>

<style lang="scss" scoped>
  .register {
    margin: 30rpx auto;
    width: 690rpx;
  }
  .toRegister {
    margin-left: 50rpx;
    cursor: pointer;
    color: blue;
  }
  .option {
    display: flex;
    justify-content: center;
  }
</style>
